#!/usr/bin/php -q

<?php
/**
 * s3cinch
 *
 * our main script file and point of call
 * for all backups. main logic for script
 * resides here
 *
 * @category   s3Cinch
 * @package    s3Cinch v1.0
 * @author     Stephen Gray <stephen@zgsolutions.co.uk>
 * @copyright  2010 Stephen Gray
 * @since      Sat 9 Jan 10 22:44
 */

/**
 * load our configuration
 */
$config = parse_ini_file('config.ini', true);

/**
 * load our classes
 */
require_once($config['dirs']['lib'].'/'.$config['dirs']['core_lib'].'/autoload.php');

/**
 * loop through all .txt files in the
 * setup directory for processing
 */
foreach (glob($config['dirs']['setup'].'/*.txt') as $fileName)
{
    /**
     * open the file and loop through
     * each line
     */
    $fileHandle = fopen($fileName, 'r');

    if ($fileHandle !== false)
    {
        while (!feof($fileHandle))
        {
            $line = fgets($fileHandle);

            /**
             * skip comments and empty lines
             */
            if (substr($line, 0, 1) == '#' || empty($line))
            {
                continue;
            }

            /**
             * if line starts with "Schedule: "
             * then we are setting a schedule for
             * this file
             */
            if (substr($line, 0, 1) == '@')
            {
                $line = substr(trim($line), 1, strlen(trim($line)));
                $dirParts = explode(' ', $line);

                switch ($dirParts[0])
                {
                    case 'schedule':
                        if (in_array($dirParts[1], array('hourly', 'daily', 'weekly', 'monthly')))
                        {
                            s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['main_file'], 'Set file\'s schedule to: '.$dirParts[1]);

                            /**
                             * if schedule is not due skip this file
                             */
                            if (!s3CinchUtils::scheduleDueNow($dirParts[1]))
                            {
                                s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['main_file'], 'Skipping file as not scheduled to run now.'."\n");
                                continue 3;
                            }
                            else
                            {
                                s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['main_file'], 'File scheduled to run now.'."\n");
                            }
                        }
                        else
                        {
                            s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['error_file'], 'Invalid schedule \''.$dirParts[1].'\', must be one of hourly, daily, weekly or monthly.'."\n");
                        }
                        break;
                    case 'bucket':
                        s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['main_file'], 'Set file\'s S3 bucket to: '.$dirParts[1]);
                        $fileBucket = $dirParts[1];
                        break;
                }
                continue;
            }

            /**
             * explode the line by set delimiter to
             * get backup type and path/database name/
             */
            $lineParts = explode($config['instruction_file']['delimiter'], $line);
            
            /**
             * trim each element
             */
            $lineParts = array_map('trim', $lineParts);

            if (in_array($lineParts[0], explode(',', $config['instruction_file']['backup_types'])))
            {
                /**
                 * make the backup class name and make
                 * sure it exists
                 */
                $className = $lineParts[0].'Backup';
                if (class_exists($className))
                {
                    /**
                     * stick the whole backup in a try/catch
                     * so we can just skip this backup if a 
                     * problem arises
                     */
                    try
                    {
                        $backupObj = new $className($lineParts);
                        $backupObj->createArchive();

                        if (isset($fileBucket))
                        {
                            $backupObj->sendFile($config['general']['keep_local_archives'], $fileBucket);
                        }
                        else
                        {
                            $backupObj->sendFile($config['general']['keep_local_archives']);
                        }

                        /**
                         * if we got here everything was a success
                         */
                        unset($backupObj);
                    }
                    catch (Exception $e)
                    {
                        /**
                         * found a problem with this backup so log
                         * it to the set error log file
                         */
                        s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['error_file'], $e->getMessage()."\n");
                    }
                }
                else
                {
                    /**
                     * must be something wrong as a class is missing
                     */
                    s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['error_file'], 'Fatal error, backup type class missing: '.$className."\n");
                }
            }
        }
    }
    else
    {
        /**
         * problem opening instruction file
         * log it
         */
        s3CinchUtils::log($config['dirs']['log'].'/'.$config['logs']['error_file'], 'Problem opening the following file, please check permissions: '.$fileName."\n");
    }
}
?>
